<?php
session_start();
require_once '../classes/Database.php';
require_once '../classes/ProductManager.php';
require_once '../classes/OrderManager.php';
require_once '../classes/CDKManager.php';
require_once '../classes/SettingsHelper.php';

// 检查管理员登录
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$productManager = new ProductManager();
$orderManager = new OrderManager();
$cdkManager = new CDKManager();

// 获取参数
$status = $_GET['status'] ?? null;
$orderNo = $_GET['order_no'] ?? null;

// 处理操作
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update_order_status') {
        $orderId = $_POST['order_id'] ?? 0;
        $newStatus = $_POST['status'] ?? '';
        
        if ($orderManager->updateOrderStatus($orderId, $newStatus)) {
            $success = "订单状态更新成功";
        } else {
            $error = "订单状态更新失败";
        }
    }
    
    if ($_POST['action'] === 'refund_order') {
        $orderId = $_POST['order_id'] ?? 0;
        
        if ($orderManager->refundOrder($orderId)) {
            $success = "订单退款成功";
        } else {
            $error = "订单退款失败";
        }
    }
}

// 获取订单列表
$orders = $orderManager->getAllOrders($status, $orderNo);
$statistics = $orderManager->getOrderStatistics();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单管理 - <?php echo htmlspecialchars(getSiteName()); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/admin.css" rel="stylesheet">
    <style>
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin: 15px 0;
        }
        .stat-card {
            background: #e9ecef;
            padding: 15px;
            border-radius: 5px;
            text-align: center;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
        }
        .stat-label {
            font-size: 14px;
            color: #6c757d;
        }
        .filter-form {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        .filter-form .form-group {
            margin-bottom: 0;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
        }
        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 5px;
            width: 500px;
        }
        .order-details {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏（移动端显示） -->
    <div class="top-navbar d-flex align-items-center justify-content-between">
        <button class="sidebar-toggle">
            <i class="fas fa-bars"></i>
        </button>
        <h5 class="mb-0">订单管理 - <?php echo htmlspecialchars(getSiteName()); ?></h5>
        <div class="text-muted small">
            <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($_SESSION['admin_username']); ?>
        </div>
    </div>

    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h4 class="mb-3">
                <i class="fas fa-cogs me-2"></i><span><?php echo htmlspecialchars(getSiteName()); ?></span>
            </h4>
            <p class="text-muted mb-0 small">欢迎, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></p>
        </div>
        
        <nav class="nav flex-column">
            <a href="index.php" class="nav-link" data-tooltip="仪表盘">
                <i class="fas fa-tachometer-alt"></i><span>仪表盘</span>
            </a>
            <a href="products.php" class="nav-link" data-tooltip="商品管理">
                <i class="fas fa-box"></i><span>商品管理</span>
            </a>
            <a href="cdks.php" class="nav-link" data-tooltip="CDK管理">
                <i class="fas fa-gift"></i><span>CDK管理</span>
            </a>
            <a href="orders.php" class="nav-link active" data-tooltip="订单管理">
                <i class="fas fa-shopping-cart"></i><span>订单管理</span>
            </a>
            <a href="payments.php" class="nav-link" data-tooltip="支付记录">
                <i class="fas fa-credit-card"></i><span>支付记录</span>
            </a>
            <a href="settings.php" class="nav-link" data-tooltip="系统设置">
                <i class="fas fa-cog"></i><span>系统设置</span>
            </a>
            <a href="logout.php" class="nav-link" data-tooltip="退出登录">
                <i class="fas fa-sign-out-alt"></i><span>退出登录</span>
            </a>
        </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-shopping-cart me-2"></i>订单管理
            </h2>
            <div class="text-muted">
                <i class="fas fa-calendar me-2"></i><?php echo date('Y年m月d日 H:i:s'); ?>
            </div>
        </div>
        <?php if (isset($success)): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <!-- 订单统计信息 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">订单统计信息</h3>
            </div>
            <div class="card-body">
                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-value"><?php echo $statistics['total_orders']; ?></div>
                        <div class="stat-label">总订单数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value"><?php echo $statistics['pending_orders']; ?></div>
                        <div class="stat-label">待支付</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value"><?php echo $statistics['paid_orders']; ?></div>
                        <div class="stat-label">已支付</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value">¥<?php echo number_format($statistics['paid_amount'], 2); ?></div>
                        <div class="stat-label">已支付金额</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-value">¥<?php echo number_format($statistics['total_amount'], 2); ?></div>
                        <div class="stat-label">总金额</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 筛选表单 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">订单筛选</h3>
            </div>
            <div class="card-body">
                <form method="GET" class="filter-form">
                    <div class="form-group">
                        <label>订单状态:</label>
                        <select name="status" class="form-control">
                            <option value="">所有状态</option>
                            <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>待支付</option>
                            <option value="paid" <?php echo $status == 'paid' ? 'selected' : ''; ?>>已支付</option>
                            <option value="completed" <?php echo $status == 'completed' ? 'selected' : ''; ?>>已完成</option>
                            <option value="refunded" <?php echo $status == 'refunded' ? 'selected' : ''; ?>>已退款</option>
                            <option value="failed" <?php echo $status == 'failed' ? 'selected' : ''; ?>>支付失败</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>订单号:</label>
                        <input type="text" name="order_no" class="form-control" value="<?php echo htmlspecialchars($orderNo ?? ''); ?>" placeholder="输入订单号">
                    </div>
                    <div class="form-group">
                        <label>&nbsp;</label>
                        <button type="submit" class="btn btn-primary">筛选</button>
                        <a href="orders.php" class="btn">重置</a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 订单列表 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">订单列表</h3>
            </div>
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th>订单号</th>
                            <th>商品名称</th>
                            <th>金额</th>
                            <th>状态</th>
                            <th>支付方式</th>
                            <th>创建时间</th>
                            <th>支付时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $order): ?>
                        <tr>
                            <td><code><?php echo htmlspecialchars($order['order_no']); ?></code></td>
                            <td>
                                <?php 
                                $product = $productManager->getProductById($order['product_id']);
                                echo $product ? htmlspecialchars($product['name']) : '未知商品';
                                ?>
                            </td>
                            <td>¥<?php echo number_format($order['total_amount'], 2); ?></td>
                            <td>
                                <?php 
                                $statusText = [
                                    'pending' => '<span style="color: orange;">待支付</span>',
                                    'paid' => '<span style="color: green;">已支付</span>',
                                    'completed' => '<span style="color: blue;">已完成</span>',
                                    'refunded' => '<span style="color: red;">已退款</span>',
                                    'failed' => '<span style="color: gray;">支付失败</span>'
                                ];
                                echo $statusText[$order['status']] ?? $order['status'];
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($order['payment_method']); ?></td>
                            <td><?php echo $order['created_at']; ?></td>
                            <td><?php echo $order['paid_at'] ?: '-'; ?></td>
                            <td>
                                <button class="btn btn-primary btn-sm" onclick="viewOrderDetails(<?php echo $order['id']; ?>)">详情</button>
                                <?php if ($order['status'] === 'pending'): ?>
                                <button class="btn btn-success btn-sm" onclick="updateOrderStatus(<?php echo $order['id']; ?>, 'paid')">标记支付</button>
                                <?php endif; ?>
                                <?php if ($order['status'] === 'paid'): ?>
                                <button class="btn btn-warning btn-sm" onclick="updateOrderStatus(<?php echo $order['id']; ?>, 'completed')">标记完成</button>
                                <?php endif; ?>
                                <?php if (in_array($order['status'], ['paid', 'completed'])): ?>
                                <button class="btn btn-danger btn-sm" onclick="refundOrder(<?php echo $order['id']; ?>)">退款</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- 订单详情模态框 -->
    <div id="orderModal" class="modal">
        <div class="modal-content">
            <h3>订单详情</h3>
            <div id="orderDetails" class="order-details">
                <!-- 订单详情内容将通过JavaScript动态加载 -->
            </div>
            <div style="text-align: right;">
                <button type="button" class="btn" onclick="closeModal()">关闭</button>
            </div>
        </div>
    </div>
    
    <!-- 更新订单状态表单 -->
    <form method="POST" id="statusForm" style="display: none;">
        <input type="hidden" name="action" value="update_order_status">
        <input type="hidden" name="order_id" id="status_order_id">
        <input type="hidden" name="status" id="status_value">
    </form>
    
    <!-- 退款表单 -->
    <form method="POST" id="refundForm" style="display: none;">
        <input type="hidden" name="action" value="refund_order">
        <input type="hidden" name="order_id" id="refund_order_id">
    </form>
    
    <script>
        function viewOrderDetails(orderId) {
            // 这里应该通过AJAX获取订单详情，简化起见显示基本信息
            var details = document.getElementById('orderDetails');
            details.innerHTML = '<p>正在加载订单详情...</p>';
            document.getElementById('orderModal').style.display = 'block';
            
            // 模拟加载订单详情
            setTimeout(function() {
                details.innerHTML = `
                    <p><strong>订单ID:</strong> ${orderId}</p>
                    <p><strong>订单详情:</strong> 这里显示订单的详细信息，包括商品信息、支付信息、CDK码等</p>
                    <p><strong>备注:</strong> 实际应用中应该通过AJAX从服务器获取完整订单信息</p>
                `;
            }, 500);
        }
        
        function updateOrderStatus(orderId, status) {
            if (confirm('确定要更新订单状态吗？')) {
                document.getElementById('status_order_id').value = orderId;
                document.getElementById('status_value').value = status;
                document.getElementById('statusForm').submit();
            }
        }
        
        function refundOrder(orderId) {
            if (confirm('确定要退款吗？此操作不可撤销！')) {
                document.getElementById('refund_order_id').value = orderId;
                document.getElementById('refundForm').submit();
            }
        }
        
        function closeModal() {
            document.getElementById('orderModal').style.display = 'none';
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            var modal = document.getElementById('orderModal');
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/admin.js"></script>
</body>
</html>
